package com.mls.wms.android.widget.inwh;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.http.RequestManager;
import com.google.zxing.client.android.Intents;
import com.mls.wms.android.R;
import com.mls.wms.android.constant.ScanTypeConstants;
import com.mls.wms.android.constant.ServicePort;
import com.mls.wms.android.extend.AnimDialogFragment;
import com.mls.wms.android.extend.BaseActivity;
import com.mls.wms.android.extend.ProblemFeedbackDialogFragment;
import com.mls.wms.android.model.CountNextRecordModel;
import com.mls.wms.android.model.InventoryQueryModel;
import com.mls.wms.android.model.ResponseResult;
import com.mls.wms.android.util.DialogUtils;
import com.mls.wms.android.util.ViewUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2015-09-24.
 */
public class InventoryCountCommodityActivity extends BaseActivity {
    private long countId = 0L;
    private String countType = "";
    private long countTaskId = 0L;
    private long locationId = 0L;
    private long skuId = 0L;
    private int scanQty = 0;

    private EditText etCountId = null;
    private EditText etSpecLocationNo = null;
    private EditText etRealLocationNo = null;
    private EditText etScanBarcode = null;
    private EditText etItemName = null;
    private EditText etScanQty = null;

    private Button btnContinue = null;
    private Button btnFeedback = null;

    private EditText selectEt = null;

    private AnimDialogFragment progressDialog = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_inventory_count_commodity);

        //弹出框
        progressDialog = new AnimDialogFragment();
        progressDialog.setResId(R.drawable.anim_progress_dialog);

        this.etCountId = (EditText) this.findViewById(R.id.act_inventory_count_commodity_count_id);
        this.etSpecLocationNo = (EditText) this.findViewById(R.id.act_inventory_count_commodity_spec_cycle_location_no);
        this.etRealLocationNo = (EditText) this.findViewById(R.id.act_inventory_count_commodity_real_count_location_no);
        this.etScanBarcode = (EditText) this.findViewById(R.id.act_inventory_count_commodity_scan_barcode);
        this.etItemName = (EditText) this.findViewById(R.id.act_inventory_count_commodity_spec_item_name);
        this.etScanQty = (EditText) this.findViewById(R.id.act_inventory_count_commodity_scan_qty);
        this.etScanQty.setText("0");

        this.btnContinue = (Button) this.findViewById(R.id.act_inventory_count_commodity_btn_continue);
        this.btnFeedback = (Button) this.findViewById(R.id.act_inventory_count_commodity_btn_feedback);

        Intent intent = getIntent();
        if (intent != null) {
            countId = intent.getLongExtra("countId", 0L);
            countType = intent.getStringExtra("countType") + "";

            this.etCountId.setText(this.countId + "");
        } else {
            Toast.makeText(this, R.string.dialog_msg_para_error, Toast.LENGTH_SHORT).show();
            this.finish();
            return;
        }

        this.getNextRecord();

        //文本框事件
        List<EditText> ets = ViewUtils.getDescendants(this, EditText.class, false);
        for (final EditText item : ets) {
            if (item.isEnabled() == true && item.getVisibility() == View.VISIBLE) {
                item.setSelectAllOnFocus(true);//获取焦点全选
                item.setOnKeyListener(new View.OnKeyListener() {
                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                            return onEnterDownEditText(v);
                        }

                        return false;
                    }
                });
                item.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_DONE) {
                            return onEnterDownEditText(v);
                        }
                        return false;
                    }
                });
                item.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                    @Override
                    public void onFocusChange(View v, boolean hasFocus) {
                        if (true == hasFocus) {
                            selectEt = item;
                        }
                    }
                });
            }
        }

        //按钮事件
        this.btnContinue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getNextRecord();
            }
        });
        this.btnFeedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProblemFeedbackDialogFragment fragment = new ProblemFeedbackDialogFragment();
                fragment.setCountId(countId);
                fragment.setLocationNo(etSpecLocationNo.getText().toString());
                fragment.setBarcode(etScanBarcode.getText().toString());
                if (TextUtils.isEmpty(etScanBarcode.getText().toString())) {
                    fragment.setQty(0);
                } else {
                    fragment.setQty(1);
                }

                fragment.show(getFragmentManager(), InventoryCountCommodityActivity.this.toString());
            }
        });
    }

    /**
     * 按下回车
     *
     * @param view
     * @return
     */
    private boolean onEnterDownEditText(View view) {
        if (view.getId() == this.etRealLocationNo.getId()) {
            isValidCountLocation();
            return true;
        } else if (view.getId() == this.etScanBarcode.getId()) {
            isValidBarcode();
            return true;
        }

        return false;
    }

    /**
     * 获取下一个任务
     */
    private void getNextRecord() {
        Map<String, String> paras = new HashMap<String, String>();
        paras.put("countId", this.countId + "");
        paras.put("countType", this.countType);
        paras.put("countTaskId", this.countTaskId == 0L ? "" : this.countTaskId + "");
        paras.put("locationId", this.locationId == 0L ? "" : this.locationId + "");
        get(ServicePort.getUrl(ServicePort.CountNextRecord), paras, new RequestManager.RequestListener() {
            @Override
            public void onRequest() {

            }

            @Override
            public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                try {
                    ResponseResult result = new ResponseResult();
                    result = result.parseJson(s);
                    if (result != null && result.getSuc() == true) {

                        CountNextRecordModel model = new CountNextRecordModel();
                        model = model.parseJson(result.getResult().toString());

                        countTaskId = model.getCountTaskId();
                        if (countTaskId == 0L) {
                            throw new Exception(getString(R.string.dialog_msg_count_task_get_fail));
                        }
                        etSpecLocationNo.setText(model.getLocationNo());
                        etRealLocationNo.requestFocus();
                    } else {
                        String message = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        DialogUtils.showOK(InventoryCountCommodityActivity.this, getResources().getString(R.string.title_text_exception), message, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                InventoryCountCommodityActivity.this.finish();
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    DialogUtils.showOK(InventoryCountCommodityActivity.this, getResources().getString(R.string.title_text_exception), e.getMessage(), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            InventoryCountCommodityActivity.this.finish();
                        }
                    });
                }
            }

            @Override
            public void onError(String s, String s2, int i) {
                DialogUtils.showOK(InventoryCountCommodityActivity.this, getResources().getString(R.string.title_text_exception), s, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        InventoryCountCommodityActivity.this.finish();
                    }
                });
            }
        }, 1);
    }

    private void isValidCountLocation() {
        if (true == TextUtils.isEmpty(this.etRealLocationNo.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_real_count_location_no_not_null), etRealLocationNo);
        } else if (false == this.etSpecLocationNo.getText().toString().trim().equals(this.etRealLocationNo.getText().toString().trim())) {
            showDialog(getResources().getString(R.string.dialog_msg_real_count_location_no_error), etRealLocationNo);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("inventoryCountId", this.countId + "");
            data.put("inventoryCountLocId", this.countTaskId + "");
            data.put("locationNo", this.etRealLocationNo.getText().toString().trim());

            get(ServicePort.getUrl(ServicePort.CountLocation), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            locationId = Long.parseLong(result.getResult());

                            etScanBarcode.requestFocus();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, etRealLocationNo);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, etRealLocationNo);
                }
            }, 1);
        }
    }


    private void isValidBarcode() {
        if (TextUtils.isEmpty(this.etScanBarcode.getText().toString())) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_not_null), etScanBarcode);
        } else {
            Map<String, String> data = new HashMap<String, String>();
            data.put("barcode", this.etScanBarcode.getText().toString().trim());

            get(ServicePort.getUrl(ServicePort.CommonGetSKU), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            InventoryQueryModel model = new InventoryQueryModel();
                            model = model.parseJson(result.getResult().toString());
                            skuId = model.getSkuId();
                            etItemName.setText(model.getItemName());

                            doSubmit();
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        showDialog(errorMsg, etScanBarcode);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    showDialog(s, etScanBarcode);
                }
            }, 1);
        }
    }

    private boolean checkSubmit() {
        if (this.locationId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_real_count_location_no_not_null), this.etRealLocationNo);
            return false;
        } else if (this.skuId == 0L) {
            showDialog(getResources().getString(R.string.dialog_msg_item_barcode_not_null), etScanBarcode);
        }


        return true;
    }


    private void doSubmit() {
        if (true == this.checkSubmit()) {
            progressDialog.show(getFragmentManager(), this.toString());
            JSONObject data = null;
            try {
                data = new JSONObject();
                data.put("countId", this.countId);
                data.put("countTaskId", this.countTaskId);
                data.put("countType", this.countType);
                data.put("locationId", this.locationId);
                data.put("skuId", this.skuId);
                data.put("barcode", this.etScanBarcode.getText().toString().trim());
                data.put("qty", 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            post(ServicePort.getUrl(ServicePort.CountInsert), data, new RequestManager.RequestListener() {
                @Override
                public void onRequest() {

                }

                @Override
                public void onSuccess(String s, Map<String, String> stringStringMap, String s2, int i) {
                    String errorMsg = null;
                    try {
                        ResponseResult result = new ResponseResult();
                        result = result.parseJson(s);
                        if (result != null && result.getSuc() == true) {
                            etScanBarcode.setText("");
                            etItemName.setText("");
                            etScanQty.setText(Integer.toString(++scanQty));

                            etScanBarcode.requestFocus();

                            progressDialog.dismiss();
                            return;
                        } else {
                            errorMsg = result == null ? getResources().getString(R.string.title_text_operate_fail) : result.getMessage();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        errorMsg = e.getMessage();
                    }

                    if (false == TextUtils.isEmpty(errorMsg)) {
                        progressDialog.dismiss();
                        showDialog(errorMsg, etScanBarcode);
                    }
                }

                @Override
                public void onError(String s, String s2, int i) {
                    progressDialog.dismiss();
                    showDialog(s, etScanBarcode);
                }
            }, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ScanTypeConstants.SCAN_BAR_CODE:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    this.selectEt.setText(bundle.getString(Intents.Scan.RESULT, ""));
                    this.selectEt.requestFocus();
                    onEnterDownEditText(this.selectEt);
                }
            default:
                break;
        }

    }

    @Override
    public void tv_back_click() {
        DialogUtils.showYesNo(this, getString(R.string.title_text_tip), getString(R.string.dialog_msg_cycle_count_back_confirm),
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                },
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        etRealLocationNo.requestFocus();
                    }
                });
    }

    @Override
    public int getTopNameResId() {
        return R.string.title_scan_one_by_one;
    }
}
